var app = getApp();
var that;
// pages/order/downline.js  
Page({
  data: {
    remark: '', //买家留言  
    address: '', //默认地址
    member_msg:'',   //商城会员个人信息
    cartids:'',  //从购物车跳入此界面传入的id数组
    goods_arr:{},  //获取的商品信息
    pwd:'', //输入的会员支付密码
    showModalStatus: false, 
    textareaStatus: false,
    order_msg:'',  //生成的订单信息 
    addr_id:'',  //从地址列表中传的地址列表
    buzu:false,  //余额不足
    index:0, //判断配送方式，
    array: ['快递', '店内自取'],
    fare:'', //运费
    base_fare:0, //基础运费
    free_shopping_money: 0,  //满xxx元免邮
    xianshi:true, //是否隐藏配送方式
    focus:true,
  },
  onLoad: function (options) {
    that=this;
    // console.log(options);
    if (options.goodsid){
      that.setData({
        goodsid: options.goodsid, optionid: options.optionid, num:options.num})
    }
    // console.log(typeof options.cartids)
    if (options.cartids) { that.setData({cartids: options.cartids.split("|")})}
    if (options.addr_id) { that.setData({ addr_id: options.addr_id }) } //地址id
    // console.log(that.data.cartids)
      that.get_goods();  //获取选择的商品
  },
  onShow: function () { 
    app.ispoint = 0;
    app.check_vs(); //检查版本
    that.setData({ member_msg: app.data.person_msg_rr })
    that.set_all();  //重新计算金额，重新刷新地址
    that.get_addr();
  },
  

  remarkInput: function (e) {
    this.setData({remark: e.detail.value,})
  },
  bindPickerChange:function(e){
    this.setData({index: e.detail.value}) 
    that.set_all(); 
  },
  s_pei:function(){
    this.setData({ xianshi: false, textareaStatus: true }) //选择配送方式
  },
  cancle:function(){
    this.setData({ xianshi: true, textareaStatus: false }) //隐藏选择配送方式
  },
  itemclick:function(e){
    that.setData({ index: e.currentTarget.id, xianshi: true, textareaStatus: false  })
    that.set_all(); 
  },
  // 加减
  changeNum: function (e) {
    // console.log(e)
    var idx = e.target.dataset.index; 
    var res = that.data.goods_arr;
    if (e.target.dataset.type == 0) {  //减法
      if (res[idx].total<= 1) {
        res[idx].total= 1
      } else { res[idx].total = parseInt(res[idx].total)-1 };
    } else {   //加法
      if (res[idx].total >= parseInt(res[idx].stock)) {
        res[idx].total = parseInt(res[idx].stock)
        if (parseInt(res[idx].stock) == 0) { res[idx].total=1 }
      }
      else { res[idx].total =parseInt(res[idx].total) +1 }
    };
    
    if (that.data.cartids!=''){ //若是购物车的改变数量时改变数据库
      that.change_car_num(res[idx].cartid, res[idx].goodsid, res[idx].total);
    }
    // console.log(res)
    that.set_all();
    that.setData({ goods_arr: res })
  },

  set_all:function(){
    var all_num=0;
    var all_total=0; 
    var fare=that.data.base_fare; //运费
    var f_money = that.data.free_shopping_money; //xxx元包邮
    console.log(fare + " " + f_money)
    for (var i = 0; i < that.data.goods_arr.length;i++){
      
      all_num += parseInt(that.data.goods_arr[i].total);
      if (parseInt(that.data.member_msg.level)> 0) {
        all_total += parseFloat(that.data.goods_arr[i].marketprice).toFixed(2) * parseInt(that.data.goods_arr[i].total);
      } else { all_total += parseFloat(that.data.goods_arr[i].productprice).toFixed(2) * parseInt(that.data.goods_arr[i].total);}

      fare += parseInt(that.data.goods_arr[i].ratio) * parseInt(that.data.goods_arr[i].total); //运费
    }

    // console.log(fare)
    that.setData({ all_n: all_num, all_t: all_total.toFixed(2), fare:fare })
    if (that.data.all_t > f_money){
      that.setData({ fare: 0 });
    }
    that.setData({ all_ttt: parseFloat(all_total + fare).toFixed(2) });  //价钱加邮费
    if (that.data.index == 0) { //快递需加运费判断
      if (that.data.member_msg.credit2 - that.data.all_ttt < 0) {
        that.setData({ buzu: true });
      } else { that.setData({ buzu: false }); }
      console.log(that.data.buzu)
    } else {   //店内自取
      if (that.data.member_msg.credit2 - that.data.all_t < 0) {
        that.setData({ buzu: true });
      } else { that.setData({ buzu: false }); }
      console.log(that.data.buzu)
    }
    // if (that.data.member_msg.credit2 - that.data.all_ttt < 0) { 
    //   that.setData({ buzu: true });
    // } else { that.setData({ buzu: false });}
  },
  
  get_goods:function(){    //获取商品,地址，会员
    var updata = { "od": app.data.openid, "id": that.data.goodsid, "optionid": that.data.optionid, "total": that.data.num};
    if (that.data.cartids!=''){
      updata = {"od": app.data.openid, "cartids": that.data.cartids}
      }
    // console.log(app.data.openid);
    // 查询商品信息时要返回店铺可用库存 需要传shop_id
    var shop_id = wx.getStorageSync('shop_id');
    updata.shop_id = shop_id;
    app.req(app.local_url + "do=order&p=confirm", updata, function (res) {
      if (res.status == 1) {
        that.setData({ goods_arr: res.result.goods, address: res.result.address, member_msg: res.result.member})
        console.log(res)
        var dispatch = res.result.dispatch;
            that.setData({ free_shopping_money: parseFloat(dispatch.secondprice), base_fare: parseFloat(dispatch.firstprice)});
            console.log(that.data.free_shopping_money);
          
        that.set_all();
      } else if (res.status == -1) {
        app.toast_up(res.result)
      } else {
        app.modal("错误提示3", "网络错误，是否重试？", function (re) {
          if (re) {
            that.get_goods()
          }
        })
      }
    })
    that.get_addr();
  },
  get_addr:function(){
    
    app.req("select_address.html", { "id": that.data.addr_id, "od": app.data.openid, }, function (res) {
        // console.log(res)
        if (res.status == "success") {
          that.setData({ address: res.mess })
        } else if (res.status == "error") {
          app.toast_up(res.mess)
        } else {
          app.modal("错误提示4", "网络错误，是否重试？", function (re) {
            if (re) {
              that.get_goods()
            }
          })
        }
      })
    
  },
  s_addr:function(e){
    wx.navigateTo({
      url: "../shop_adr/shop_adr?from=order"
    }) 
  },
  change_car_num:function (id, goodsid, num) {
    app.req(app.local_url + "do=shop&p=cart&op=updatenum", { "od": app.data.openid, "id": id, "goodsid": goodsid, "total": num, }, function (res) {
      console.log(res);
      if (res.status == 1) {
      } else if (res.status == -1) {
        app.toast_up(res.result)
      } else {
        app.modal("错误提示5", "网络错误，是否重试？", function (re) {
          if (re) {
            that.change_car_num(id, goodsid, num)
          }
        })
      }
    })
  },
  bindCheckout: function (e) { //立刻结算,生成订单
   

    if (app.data.over_vs) { Show.alertShow(that, "info", "猫托托出新版本了！请重新搜索进入！");return}

    app.data.formid = e.detail.formId;
    if (app.globalData.userInfo.phone == '') {     //没有电话设置电话，有电话就返回
      wx.navigateTo({
        url: '../personal_mse/phone?op=op',
      });return;
    }
    // console.log(that.data.address);
    if (!that.data.address&&that.data.index==0) { app.toast_up('未选择地址'); return; }
    if (that.data.index == 0 && that.data.address) {
      if (that.data.address.province!="北京"){
        app.toast_up('只能配送北京市！'); return;
      }
    }
    var fromcart = 0; //是否来自购物车
    if (that.data.cartids != "") { fromcart = 1 }
    var goods = "";
    for (var i = 0; i < that.data.goods_arr.length; i++) {
      goods += that.data.goods_arr[i].goodsid + "," + that.data.goods_arr[i].optionid + "," + that.data.goods_arr[i].total + "|"
    }
    goods = goods.substring(0, goods.length - 1)
    // console.log(fromcart);
    var dispatchid = 2;//快递
    if (parseInt(that.data.index) == 1) { dispatchid = 1 } //店内自取

      
    console.log('kdk' + app.ispoint)
    if (app.ispoint == 1) { return; } else { app.ispoint = 1; }//弹出支付框后就不允许执行了
    
    // 录单添加 shop_id bzs,20180814
    var shop_id = wx.getStorageSync('shop_id');
    app.req(app.local_url + "do=order&p=confirm&op=create", { "od": app.data.openid, "addressid": that.data.address.id, "remark": that.data.remark, "fromcart": fromcart, "cartids": that.data.cartids, "goods": goods, "dispatchid": dispatchid,"fare":that.data.fare,"shop_id":shop_id}, function (res) {
      console.log(res)
     
      if (res.status == 1) {
        that.get_shop_order(res.result.orderid) //获取订单详情
      } else if (res.status == -1 || res.status == 0) {
        app.ispoint = 0;
        app.toast_up(res.result)
      } else {
        app.ispoint = 0;
        app.modal("错误提示6", "网络错误，是否重试？", function (re) {
          if (re) {
            that.bindCheckout()
          }
        })
      }
    })
  },
  coudan:function(e){
    // console.log(that.data.goodsid)
    // console.log(that.data.optionid)
    // console.log(that.data.goods_arr[0].total)
  
    if (that.data.cartids == "") {    //来自购物卡，不必加入购物车了
      app.req(app.local_url + "do=shop&p=cart&op=add", { "od": app.data.openid, "optionid": that.data.optionid, "id": that.data.goodsid, "total": that.data.goods_arr[0].total}, function (res) {
        console.log(res)
        if (res.status == 1) {
          wx.switchTab({ url: '../shop/shop', }) //跳回商城首页
        } else if (res.status == 0) {
          app.toast_up(res.result)
        } else {
          app.modal("错误提示7", "网络错误，是否重试？", function (re) {
            if (re) {
              that.addShopCar(e)
            }
          })
        }
      })
    } else { wx.switchTab({ url: '../shop/shop', })}
   
  },
  cle: function (){
    that.util("close")
  },
  input_pwd: function (e) {   //会员支付
    that.setData({ pwd: e.detail.value.trim() })
    if (that.data.pwd.length == 6 && app.data.pointed == true) {//密码位数够了就判断
      that.setData({ focus: false })
      app.data.pointed = false;   //避免快速点击调用两次方法
      setTimeout(function () { app.data.pointed = true; }, 1500)

      app.req("pay_from_member.html", { "ordersn": that.data.order_msg.ordersn, "price": that.data.order_msg.price, "pwd": that.data.pwd, "type": 'shop', "openid": app.data.openid, 'shop_id':wx.getStorageSync('shop_id')}, function (res) {
        if (res.status == "success") {
          that.util('close')//关闭支付弹窗
          app.toast_up(res.mess)
          that.huidiao(); //会员支付后应回调修改库存，微信支付后台自动回调,之后调用success函数
          app.get_msg_rr();  //充值成功后刷新个人在人人商城的信息
        
        } else if (res.status == "error") {
          app.ispoint = 0;
          app.toast_up(res.mess)
          that.setData({ pwd: '' })
        } else {
          app.ispoint = 0;
          app.modal("错误提示8", "网络错误，是否重试？", function (re) {
            if (re) {
              that.input_pwd(e)
            }
          })
        }
      })
    }
  },
  get_shop_order: function (orderid) {
    app.req("get_shop_order.html", { "orderid": orderid }, function (res) {
      if (res.status == "success") {
        // console.log(res)
        that.setData({ order_msg: res.mess })        
        that.wx_pay();   //获取订单详情后支付
      } else if (res.status == "error") {
        app.ispoint = 0;
        app.toast(res.mess)
      } else {
        app.ispoint = 0;
        app.modal("错误提示9", "网络错误，是否重试？", function (re) {
          if (re) {
            that.get_shop_order(orderid)
          }
        })
      }
    })
  },
  wx_pay: function () {     
    if (parseInt(that.data.member_msg.level) > 0) {
        if (parseFloat(that.data.member_msg.credit2) - parseFloat(that.data.order_msg.price) < 0) {
          that.setData({ buzu: true });
        } else { that.setData({ buzu: false }); }
        console.log(that.data.buzu)

      that.setData({showModalStatus: true}); return} //如果是会员，就会员支付
    app.req("pay_shop.html", { "openid": app.data.openid, 'price': that.data.order_msg.price, 'ordersn': that.data.order_msg.ordersn,"shop_id":wx.getStorageSync('shop_id') }, function (res) {
      if (res.status == "success") {
        
        wx.requestPayment(
          {
            'timeStamp': res.mess.timeStamp,
            'nonceStr': res.mess.nonceStr,
            'package': res.mess.package,
            'signType': res.mess.signType,
            'paySign': res.mess.paySign,
            'success': function (re) {
              that.success();
            },
            'fail': function (re) {
              app.ispoint = 0;
              app.toast_up("支付失败！")
            },
            'complete': function (res) { }
          })
      } else if (res.status == "error") {
        app.toast_up(res.mess)
      } else {
        app.modal("错误提示10", "网络错误，是否重试？", function (re) {
          if (re) {
            that.wx_pay()
          }
        })
      }
    })
  },
  success:function(){
    var pages = getCurrentPages()
    var prevPage = pages[pages.length - 2]   //上一个页面
    prevPage.setData({ saled:true});
    app.orderSign(that.data.order_msg.price, "商品消费", that.data.order_msg.ordersn); //发送微信模板消息
    if (that.data.cartids != ""){that.del_cart();}  //删购物车
    setTimeout(function () {
      wx.redirectTo({
        url: './buy_success?orderid=' + that.data.order_msg.id+"&keyword="+"猫"
      })//支付成功传第订单号进入订单详情
    }, 1000)
  },
  huidiao:function(){  //回调修改库存
    app.req(app.local_url + "do=order&p=pay&op=complete&type=credit", { "orderid": that.data.order_msg.id, "od": app.data.openid}, function (res) {
      console.log(res)
      if (res.status == 1) {
        that.success();
      } else if (res.status == -1) {
        app.toast(res.result)
      } else {
        app.modal("错误提示-11", "网络错误，是否重试？", function (re) {
          if (re) {
            that.huidiao()
          }
        })
      }
    })
  },
  del_cart:function(){  //若是从购物车进来支付成功删除购物车
    app.req(app.local_url + "do=shop&p=cart&op=remove", { "od": app.data.openid, "ids": that.data.cartids }, function (res) {
      if (res.status == 1) {

      } else if (res.status == 0) {
        app.toast_up(res.result)
      } else {
        app.modal("错误提示", "网络错误，是否重试？", function (re) {
          if (re) {
            that.del_cart()
          }
        })
      }
    })
  },
  util: function (currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例 
    var animation = wx.createAnimation({
      duration: 200, //动画时长 
      timingFunction: "linear", //线性 
      delay: 0 //0则不延迟 
    });

    // 第2步：这个动画实例赋给当前的动画实例 
    this.animation = animation;

    // 第3步：执行第一组动画 
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存 
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画 
    setTimeout(function () {
      // 执行第二组动画 
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象 
      this.setData({
        animationData: animation
      })

      //关闭 
      if (currentStatu == "close") {
        app.ispoint = 0;
        that.setData({ focus: false })
        this.setData({showModalStatus: false });
      }
    }.bind(this), 200)
    // 显示 
    if (currentStatu == "open") {
      this.setData( { showModalStatus: true});
      setTimeout(function () {
        that.setData({ focus: true });//出现输入密码时获取焦点
      }, 1000);
    }
  } 
});
